"use strict";

/**
200: OK - 请求成功
201: Created - 已创建新资源
400: Bad Request - 无法理解的请求
401: Unauthorized - 未经授权的访问
403: Forbidden - 禁止访问
404: Not Found - 未找到请求的资源
500: Internal Server Error - 服务器内部错误 */

import ExplainModel from "../../models/v3/explain";
const request = require("request"); //服务端请求
const axios = require("axios"); //高级接口请求替代request
const cheerio = require("cheerio"); //抓取获取的内容（类似jquery）
const formidable = require("formidable");//用于处理表单数据。它提供了一种方便的方式来解析表单数据，包括文件上传、文本字段等。通过使用 formidable，你可以轻松地处理表单提交，从而处理用户提交的数据。
const fs = require("fs");//用于处理文件操作。fs 是 File System 的缩写，提供了一组用于读取、写入、删除、修改和操作文件的方法

const jsonErr1 = {
  status: 0,
  type: "FORM_DATA_ERROR",
  message: "表单信息错误",
};

class Explain {
  constructor() { }
  async getExpalin(req, res, next) {
    try {
      const explain = await ExplainModel.findOne();
      res.send(explain.data);
    } catch (err) {
      console.log("获取服务中心数据失败", err);
      res.send({
        status: 0,
        type: "ERROR_GET_SERVER_DATA",
        message: "获取服务中心数据失败",
      });
    }
  }

  async getLiliInfo(req, res, next) {
    try {
      var ip = getClientIp(req);
      // ip = "120.236.199.66";//测试用ip
      console.log(ip);
      axios //接口参数是json的形式
        .get("https://www.ip138.com/iplookup.php?ip=" + ip, {}) //www.quword.com/root/search?wd=propellent
        .then(function (response) {
          const $ = cheerio.load(response.data);
          let location = $(".active").find("span").text();
          console.log(location);
          console.log(ip);
          const currentDate = new Date();
          const options = {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            weekday: 'long',
            hour: 'numeric',
            minute: 'numeric',
            second: 'numeric',
            timeZone: 'Asia/Shanghai',
            timeZoneName: 'short',
          };
          const formatter = new Intl.DateTimeFormat('en-US', options);
          const formattedDate = formatter.format(currentDate);
          console.log(formattedDate);


          var data = "";
          fs.access("../liliInfo.txt", fs.constants.F_OK, (err) => {
            if (err) {//不存在创建文件
              if (err.code === 'ENOENT') {
                console.log('File does not exist.');
                fs.writeFile("../liliInfo.txt", "", function (err) { });
              } else {
                console.error('Error occurred:', err);
              }
            } else {//存在读取文件
              console.log('File exists.');
              data = fs.readFileSync("../liliInfo.txt");
              data = data + formattedDate + "｜" + ip + "｜" + location + "\n";
              fs.writeFile("../liliInfo.txt", data, function (err) {
                if (err) {
                  return console.error(err);
                }
              });
            }
          });

          res.status(200);
          res.send({ img: "ok", qrcode: "ok" ,message:"到上级目录里查看记录"});
        })
        .catch(function (error) {
          // 请求失败处理
          // console.log(error);
          console.log("查询IP是'" + ip + "' getLiliInfo请求失败,请打开注释查看原因");
          res.status(500);
          res.send({ error: "查询IP是'" + ip + "' getLiliInfo请求失败:" + error });
        });
    } catch (err) {
      console.log("获取服务中心数据失败", err);
      res.send({
        status: 0,
        type: "ERROR",
        message: err.message,
      });
    }
    function getClientIp(req) {
      console.log("getLiliInfo正在获取IP地址");
      return (
        req.headers["x-forwarded-for"] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress
      );
      // return req.ip
    }
  }

  async getJuheIpArea(req, res, next) {
    try {
      var ip = getClientIp(req);
      console.log(ip);
      /** 
      let url =
        "http://apis.juhe.cn/ip/ipNewV3?ip=" +
        ip +
        "&key=d282077a2e5367fdd96a6a3d6a37e206";
      request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
          console.log(body); // 请求成功的处理逻辑，注意body是json字符串
          // res.status(200);
          // res.send({ body: JSON.parse(body), ip: ip });
        }
      });//聚合查的太大了
      */
      axios //接口参数是json的形式
        .get("https://www.ip138.com/iplookup.php?ip=" + ip, {}) //www.quword.com/root/search?wd=propellent
        .then(function (response) {
          // console.log(response.data);
          const $ = cheerio.load(response.data);
          // console.log($);
          let location = $(".active").find("span").text();
          console.log(location);
          res.status(200);
          res.send({ location: location, ip: ip });
        })
        .catch(function (error) {
          // 请求失败处理
          // console.log(error);
          console.log("查询IP是'" + ip + "' getJuheIpArea请求失败,请打开注释查看原因");
          res.status(500);
          res.send({ error: "查询IP是'" + ip + "' getJuheIpArea请求失败" + error });
        });
    } catch (err) {
      console.log("获取服务中心数据失败", err);
      res.send({
        status: 0,
        type: "ERROR",
        message: err.message,
      });
    }
    function getClientIp(req) {
      console.log("getJuheIpArea正在获取IP地址");
      return (
        req.headers["x-forwarded-for"] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress
      );
      // return req.ip
    }
  }

  async getJuhePhoneArea(req, res, next) {
    try {
      axios //接口参数是json的形式
        .get(
          "http://apis.juhe.cn/mobile/get?phone=" +
          req.query.phone +
          "&dtype=&key=c35a0335912d66950b92309be39e51aa",
          {}
        )
        .then((response) => res.send(response.data))
        .catch(function (error) {
          // 请求失败处理
          console.log(error);
        });
    } catch (err) {
      console.log("获取服务中心数据失败", err);
      res.send({
        status: 0,
        type: "ERROR",
        message: err.message,
      });
    }
  }
  async postJuhePhoneArea(req, res, next) {
    const form = new formidable.IncomingForm();
    form.parse(req, async (err, fields, files) => {
      if (err) {
        res.send(jsonErr1);
        return;
      }
      const { phone, status = 1 } = fields;
      try {
        axios //接口参数是json的形式
          .get(
            "http://apis.juhe.cn/mobile/get?phone=" +
            phone +
            "&dtype=&key=c35a0335912d66950b92309be39e51aa",
            {}
          )
          .then((response) => res.send(response.data))
          .catch(function (error) {
            // 请求失败处理
            console.log(error);
          });
      } catch (err) {
        console.log("获取服务中心数据失败", err);
        res.send({
          status: 0,
          type: "ERROR",
          message: err.message,
        });
      }
    });
  }
  async postQuciRoot(req, res, next) {
    const form = new formidable.IncomingForm();
    form.parse(req, async (err, fields, files) => {
      if (err) {
        res.send(res.send(jsonErr1));
        return;
      }
      const { word, status = 1 } = fields;
      try {
        axios //接口参数是json的形式
          .get("https://www.quword.com/root/search?wd=" + word, {})
          .then(function (response) {
            // console.log(response.data);
            const $ = cheerio.load(response.data);
            // console.log($);
            const classk = $(".logo-down");
            console.log(classk.text()); //截取class内容
            const listRoot = $("h2");
            var roots = [];
            listRoot.each(function (idx, h2) {
              const listP = $(h2).nextUntil("h2");
              var origins = [];
              listP.each(function (idx, p) {
                // var listItem = $(p).html().split("<br>").filter(item => item && item.trim())
                // listItem.forEach(function (item){
                //   origins.push(item);
                // })
                origins.push($(p).text());
              });
              roots.push({ root: $(h2).text(), origin: origins });
            });
            res.send(roots);
          })
          .catch(function (error) {
            // 请求失败处理
            console.log(error);
          });
      } catch (err) {
        console.log("获取服务中心数据失败", err);
        res.send({
          status: 0,
          type: "ERROR",
          message: err.message,
        });
      }
    });
  }
}

export default new Explain();
